package com.lx.plugin;

import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;

import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * 自定义插件(将名称下划线转为驼峰命名)
 * \@Intercepts配置该插件的作用点（实际上就是作用的函数调用点）
 * @author 段誉
 * @create 2018-12-17 13:25
 */
@Intercepts({@Signature(
        type = ResultSetHandler.class,
        method = "handleResultSets",
        args = {Statement.class})})
public class MyPlugin implements Interceptor {
  @Override
  @SuppressWarnings("unchecked")
  public Object intercept(Invocation invocation) throws Throwable {

    List result = (List) invocation.proceed();
    if (result != null && result.size() > 0) {

      if (result.get(0) instanceof Map) {

        List resList = new ArrayList();
        for (Map el: (List<Map>) result) {

          Map map = new HashMap(el.keySet().size());
          for (String key: (Set<String>) el.keySet()) {
            map.put(getCamelKey(key), el.get(key));
          }

          resList.add(map);
        }

        return resList;
      }

    }
    return result;
  }

  /**
   * 调用Plugin.wrap静态方法来创建代理类
   * @param target
   * @return
   */
  @Override
  public Object plugin(Object target) {
    return Plugin.wrap(target, this);
  }

  @Override
  public void setProperties(Properties properties) {

  }

  /**
   * 将下划线修改为驼峰命名
   * @param key
   * @return java.lang.String
   * @author 段誉
   * @date 2018/12/17 13:32
   * @since 1.0.0
   */
  private String getCamelKey(String key) {
    String[] split = key.split("_");
    StringBuffer camelKey = new StringBuffer();
    for (int i = 0, j = split.length; i < j; i++) {
      if (i != 0) {
        camelKey.append(split[i].substring(0, 1).toUpperCase());
        camelKey.append(split[i].substring(1, split[i].length()));
      } else {
        camelKey.append(split[i]);
      }
    }
    return camelKey.toString();
  }
}
